/**
 * 
 * @param argc
 * @param argv
 */


#include "skl.h"
#include "skl_core.h"
/**
 * 
 * @param argc
 * @param argv
 * @return 
 */
void main(int argc, char *argv[]) {
    init_entry();
    int ret = handle_command(argc,argv);
    if(ret == RET_SUCCESS){
        return;
    }
    if (argc != 2) {
        error_exception("Usage:%s filename!", argv[0]);
        return;
    }
    handle_run_command(argv[1]);
}
void init_entry(){
    setvbuf(stdout, NULL, _IONBF, 0);
}
int handle_command(int argc, char *argv[]){
    int opt=0;
    int ret = RET_FAIL;
    extern char* optarg;
    while((opt=getopt(argc,argv,"vahf:"))!=-1){
        switch(opt)
        {
            case 'v':
                handle_version_command();
                ret = RET_SUCCESS;
                break;
            case 'a':
                handle_author_command();
                ret = RET_SUCCESS;
                break;
            case 'f':
                handle_run_command(optarg);
                ret = RET_SUCCESS;
                break;
            case 'h':
                handle_help_command();
                ret = RET_SUCCESS;
                break;
        }
    }
    return ret;
}

void handle_version_command(){
    printf("SKL version:%s%s",SKL_VERSION,EOL);
    printf("SKL version num:%d%s",SKL_VERSION_NUM,EOL);
}

void handle_author_command(){
    printf("SKL author:%s%s",SKL_AUTHOR,EOL);
}

void handle_help_command(){
    char *help = "Usage: skl [options] [-f] <file>\n"\
    "-a\t\tShow the author.\n"\
    "-v\t\tShow the version.\n"\
    "-f <file>\tParse and execute <file>.\n";
    printf("%s%s", help,EOL);
}

void handle_run_command(char *filename){
    FILE *input;
    input = fopen(filename, FILE_OPT_READ);
    if (is_empty(input)) {
        error_exception("Filename:%s not found!", filename);
        return;
    }
    yyin = input;
    init_compiler(filename);
    if (yyparse()) {
        error_exception("System parse failed!");
        return;
    }
    execute();
    fclose(input);
}